package Homework;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;

public class FileCopy extends Thread{
    //源文件
    public File oldFile;
    //目标文件
    public File newFile;

    public FileCopy(String oldFile,String newFile){
        this.oldFile = new File(oldFile);
        this.newFile = new File(newFile);
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(oldFile);
            fileOutputStream = new FileOutputStream(newFile);
            byte[] bytes = new byte[2];
            //返回每次读取的长度
            int length;
            //得到源文件的字节长度
            long len = oldFile.length();

            double temp = 0;
            //数据格式化
            DecimalFormat fd = new DecimalFormat("##.##%");

            while ((length = fileInputStream.read(bytes))!= -1){
                fileOutputStream.write(bytes,0,length);
                //把每次读取到的数据累加
                temp = temp+length;
                double d = temp/len;
                System.out.println(oldFile.getName()+"文件复制到"+newFile.getName()+"已经复制了"+fd.format(d));
            }
            System.out.println(oldFile.getName()+"文件复制完毕");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
